<?php

namespace App\Controllers\v1;

use App\Services\HelpService;
use App\Services\RechargeService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use common\utils\SysCode;
use App\Controllers\BaseController;
use App\Services\FundsService;
use App\Services\WithdrawService;
use App\Services\MoneyService;

class BankController extends BaseController
{
    //额度转化接口
    public function transform(Request $request)
    {
        $rule = [
            'cid' => 'required',//子钱包partner_id
            'type' => 'required',//1-主转子，2-子转主
            'amount' => 'required',//真实金额
        ];
        $user = Auth::user();
        $checkParams = $this->validate($request, $rule);
        $result = FundsService::exchange($user, $checkParams);
        return $result;
    }

    //可以获取的优惠和打码量计算
    public function thirdGame(Request $request)
    {
        $user = Auth::user();
        $game = $request->input("g", "Pt");
        $method = $request->input("c", "");
        return $user;
    }


    //获取存款优惠
    public function getDepositHelp(Request $request)
    {
        $apply = $request->input("category", 3);
        $type = $request->input('type', 307);
        $pf = $request->input("pf", 'pc');
        $select = ['id', 'name', 'content'];
        $where = [
            ['category', '=', $apply],
            ['type', '=', $type],
            ['status', '=', 1],
            ['platform', '=', $pf],
        ];
        $data = HelpService::getDepositData($select, $where);
        return $data;
    }


    //获取用户信息
    public function getWithdraw()
    {
        $user = Auth::user();
        $userId = $user['id'];
        $balance = WithdrawService::getWalletInfo($userId);
        $noFeeTime = WithdrawService::getNoFeeTime($userId);
        $bankList = WithdrawService::cardList($userId);//提现银行卡列表
        $resultData = [
            'balance' => amount_format($balance['balance']),
            'no_fee_time' => $noFeeTime['no_fee_tims'],
            'min' => amount_format($noFeeTime['min']),
            'max' => amount_format($noFeeTime['max']),
            'bank_list' => empty($bankList) ? [] : $bankList
        ];
        return $resultData;
    }

    //提款预申请页面
    public function getWithdrawInfoDetail(Request $request)
    {
        $user = Auth::user();
        $userId = $user['id'];
        $this->validate($request, [
            'password' => 'required',
            'money' => 'required',
        ]);
        $password = $request->input("password", "");
        if (!MoneyService::validPassword($userId, $password)) {
            return error_exit(SysCode::USER_WITHDRAW_PASSWORD_ERROR);
        }

        $withdrawFee = WithdrawService::getwithDrawFee($userId);
        $money = $request->input('money', 0);
        $admin_fee = $withdrawFee['admin_fee'];
        $fee = $withdrawFee['withdraw_fee'];
        $coupon_fee = $withdrawFee['coupon'];
        $result = $fee == 0 && $admin_fee == 0 ? 1 : 0;
        $widthList = [];
        if (isset($withdrawFee['list']) && is_array($withdrawFee['list'])) {
            foreach ($withdrawFee['list'] as $k => $v) {
                $list['start_time'] = $v['start_time'];
                $list['end_time'] = $v['end_time'];
                $list['deposit_money'] = amount_format($v['deposit']);
                $list['coupon_money'] = amount_format($v['coupon']);
                $list['is_pass'] = $v['is_pass'];
                $valid_bet = amount_format($v['valid_bet']);
                $widthdraw_bet = isset($v['withdraw_bet_principal']) ? amount_format($v['withdraw_bet_principal']) : 0;
                $withdraw_bet_coupon = isset($v['withdraw_bet_coupon']) ? amount_format($v['withdraw_bet_coupon']) : 0;
                $list['withdraw_bet'] = $widthdraw_bet;
                $list['withdraw_bet_coupon'] = $withdraw_bet_coupon;
                $list['withdraw_bet_ispass'] = $valid_bet >= $widthdraw_bet ? 1 : 0;
                $list['withdraw_bet_coupon_ispass'] = $valid_bet >= $withdraw_bet_coupon ? 1 : 0;
                $list['valid_bet'] = amount_format($v['valid_bet']);
                $list['deduct_admin_fee'] = amount_format($v['deduct_admin_fee']);
                $list['deduct_coupon'] = amount_format($v['deduct_coupon']);
                $widthList[] = $list;
            }
        }
        $data = [
            'admin_fee' => $admin_fee,//行政费
            'fee' => $fee,//手续费
            'coupon_fee' => $coupon_fee,//扣除优惠费用
            'money' => $money,//提款金额
            'result' => $result, //1-通过 0-不通过
            'list' => $widthList,
        ];
        return $data;
    }


    //提款确认接口
    public function getWithdrawConfirm(Request $request)
    {
        $user = Auth::user();
        $user_id = $user['id'];
        $this->validate($request, [
            'withdraw_money' => 'required',
            'withdraw_pwd' => 'required',
            'withdraw_card' => 'required',
        ]);

        //检测是否已经绑定邮箱或者手机号码
        $check_property = WithdrawService::getProperty($user_id);
        if (empty($check_property['email']) && empty($check_property['mobile'])) {
            error_exit(SysCode::BANK_EXCHANGE_NOT_FIND_EMAIL_MOBILE);
        }

        //校验密码的正确性
        $password = $request->input("withdraw_pwd", "");
        if (!MoneyService::validPassword($user_id, $password)) {
            return error_exit(SysCode::USER_WITHDRAW_PASSWORD_ERROR);
        }
        //获取银行卡信息
        $withdraw_card = $request->input("withdraw_card", 0);
        //备注
        $remark = $request->input("remark", "");

        $fee = WithdrawService::getwithDrawFee($user_id);
        $withdraw_money = $request->input('withdraw_money', 0);
        $withdraw_money = amount_format($withdraw_money, true);
        if ($withdraw_money < $fee['each_min_out']) {
            error_exit(SysCode::BANK_EXCHANGE_MONEY_MIN, ['min' => amount_format($fee['each_min_out'])]);
        }
        if ($withdraw_money > $fee['each_max_out']) {
            error_exit(SysCode::BANK_EXCHANGE_MONEY_MAX, ['max' => amount_format($fee['each_max_out'])]);
        }
        if ($fee['withdraw_times'] > $fee['day_out_times']) {
            error_exit(SysCode::BANK_EXCHANGE_MONEY_DAY_LIMIT, ['time' => amount_format($fee['day_out_times'])]);
        }


        //判断申请金额和出款费大小  总和 = 行政功能费
        $fee_total = $fee['admin_fee'] + $fee['coupon'] + $fee['withdraw_fee'];
        if ($fee_total > $withdraw_money) {
            error_exit(SysCode::BANK_WITHDRAW_MONEY_LIMIT, ['withdraw_money' => amount_format($withdraw_money), 'fee_total' => amount_format($fee_total)]);
        }

        //判断是否已经有生成的订单
        $checkExit = WithdrawService::checkExitWithdrawOrder($user_id);
        if ($checkExit) {
            return error_exit(SysCode::BANK_WITHDRAW_ORDER_EXIST, ['order_number' => $checkExit['order_number']]);
        }

        $data = MoneyService::addWithdrawOrder($user, $withdraw_money, $withdraw_card, $fee, $request->getClientIp(), $remark);

        return $data;
    }


    //跳转提款页面获取,提款信息
    public function getWithdrawInfoList()
    {
        $user = Auth::user();

        $userId = $user['id'];
        //获取钱包信息
        $walletInfo = WithdrawService::getWalletInfo($userId);

        //初始化值
        $arr = [
            'type' => 0,
            'balance' => $walletInfo['balance'],
            'name' => $user['true_name'],
            'withdraw_money' => [
                'min' => 10,
                'max' => $walletInfo['balance'],
            ],
            'withdraw_card' => [

            ],
            "info" => [
                "counter_fee" => "12",
                "government_fee" => "22",
                "Discount" => "0"
            ],
            'one_status' => 1
        ];

        //判断是否已经有生成的订单
        $checkExit = WithdrawService::checkExitWithdrawOrder($userId);
        if ($checkExit) {
            return error_exit(SysCode::BANK_WITHDRAW_ORDER_EXIST, ['order_number' => $checkExit['order_number']]);
        }
        //计算提款稽核对应的手续费,行政费,
        $withdrawFee = WithdrawService::getwithDrawFee($userId);


        //根据层级实时计算出对应的最大最小提款限额
        $levelConfig = WithdrawService::getLevelConfig($userId);
        $arr['withdraw_money']['min'] = $levelConfig['withdraw_min_limit'];
        $arr['withdraw_money']['max'] = $levelConfig['withdraw_max_limit'];
        //获取对应的银行卡信息
        $rs = WithdrawService::cardList($userId);//提现银行卡列表


        if ($rs) {
            $arr1 = [];
            foreach ($rs as $v) {
                if ($v['state'] == 'enabled') {
                    $v['card_number'] = $v['card'];
                    array_push($arr1, $v);
                }
            }
            //是否是第一次提现
            $one_s = WithdrawService::checkFirstWithdraw($userId);
            if ($one_s[0]['onepus'] > 0) {
                $arr['one_status'] = 0;
            } else {
                $arr['one_status'] = 1;
            }
            $arr['withdraw_card'] = $arr1;
            $arr['type'] = empty($arr1) ? 0 : 1;
        }
        return $arr;
    }

    /**
     * 获取充值信息
     * 线上 线下 充值信息
     * 充值说明
     */
    public function getRecharge(Request $request){
        $user = Auth::user();
        $pf = $request->input('type', 1);//平台类型 1 pc | 2 h5
        return RechargeService::getRecharge($user, $pf);
    }

    /**
     * 提交充值
     * 线上 线下
     */
    public function putRecharge(Request $request){
        $user = Auth::user();
        $params = $this->validate($request, [
            'type' => 'required',//充值类型 1：线下充值，公司入款  3:第三方平台在线支付 4：网银支付 （暂未开通）
            'money' => 'required',
        ]);
        return RechargeService::putRecharge($user, $request->input());
    }
    //获取存提记录
    public static function getUserMoneyList(Request $request)
    {

        $user = Auth::user();
        $user_id = $user['id'];
        $start_time = $request->input("start_time", date("Y-m-d 00:00:00"));
        $end_time = $request->input("end_time", date("Y-m-d 23:59:59"));
        $page = $request->input("page", 1);
        $page_size = $request->input("page_size", 15);
        $data = MoneyService::getUserMoneyList($user_id, $start_time, $end_time, $page, $page_size);
        return $data;
    }


}
